const fs = require('fs');
const http = require('http');
const url = require('url')

// 创建一个f服务器
let server = http.createServer((req, res) => {
    let params = url.parse(req.url, true, true)
    console.log('get request', req.url)

    let filename = params.pathname
    let realPath = __dirname + filename; // __dirname  为当前目录
    let contentType = 'text/html';
    if (filename === '/favicon.ico') {
        contentType = 'image/x-icon'
    }


    // fs.readFile(文件路径，字符编码，回调函数)
    fs.readFile(realPath, contentType.indexOf('image') > -1 ? null : "utf-8", (err, data) => {
        if (err) {
            throw err;
        }
        res.writeHead(200, {"content-type": contentType});
        res.write(data);
        res.end();
    })

})

// 设置端口号
server.listen(8080);
console.log('app started')